<?php


namespace app\admin\controller;


use app\admin\model\SystemAdmin;
use app\common\controller\AdminController;
use think\captcha\facade\Captcha;
use think\facade\Env;
use UserHub\Client;

/**
 * Class Login
 * @package app\admin\controller
 */
class Login extends AdminController
{

    /**
     * 初始化方法
     */
    public function initialize()
    {
        parent::initialize();
        $action = $this->request->action();
        if (!empty(session('admin')) && !in_array($action, ['out'])) {
            $adminModuleName = config('app.admin_alias_name');
            $this->success('已登录，无需再次登录', [], __url("@{$adminModuleName}"));
        }
    }

    /**
     * 用户登录
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $code = $this->request->param('code');

        // 实例化客户端,传入相关参数
        $user_hub_client = new Client([
            'key' => Env::get('user_hub.key'),
            'secret' => Env::get('user_hub.secret'),
            'host' => 'http://user-hub.ulthon.com',     // http://user-hub.ulthon.com ,填入自己搭建好的UserHub站点地址,需要带协议
        ]);
        if (empty($code)) {
            // 跳转登录
            $url = $user_hub_client->getBowserRedirectUrl($this->request->url(true));
            $this->assign('login_url', $url);
        } else {
            // 获取用户信息
            $user_info = $user_hub_client->getUserinfoByCode($code);

            $admin = SystemAdmin::where(['uid' => $user_info['uid']])->find();
            if (empty($admin)) {
                $admin = new SystemAdmin;
                $admin->auth_ids = 6;
                $admin->uid = $user_info['uid'];
                $admin->username = $user_info['account'];
                $admin->head_img = $user_info['avatar'];
                $admin->status = 1;
                $admin->nickname = $user_info['nickname'];
                $admin->save();
            }

            if ($admin->status == 0) {
                $this->error('账号已被禁用');
            }

            $admin->login_num += 1;
            $admin->save();
            $admin = $admin->toArray();
            unset($admin['password']);
            $admin['expire_time'] = true;
            session('admin', $admin);
            $this->success('登录成功', [], __url('admin/Index/index'));
        }

        return $this->fetch();
    }

    /**
     * 用户退出
     * @return mixed
     */
    public function out()
    {
        session('admin', null);
        $this->success('退出登录成功');
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function captcha()
    {
        return Captcha::create();
    }
}
